/** @file typo.c
 *
 * @brief Echos characters back with timing data.
 *
 * @author Nora Tarano <ntarano@andrew.cmu.edu>
 * @author Yuan Meng <yuanm@andrew.cmu.edu>
 * @author Yipeng Yun <yipengy@andrew.cmu.edu>
 *
 * @date Nov 17, 2011
 *
 * Links to libc.
 */

#include <unistd.h>
#include <stdio.h>

#define BUFF_LEN 128

int main(int argc, char** argv)
{
	int length;
	char buffer[BUFF_LEN];
	unsigned long before;
	unsigned long after;
	const char *prompt = "> ";
	int to_write, written;

	while(1){
		to_write = 2;
		written = 0;
		// print '>'
		while((written = write(STDOUT_FILENO, &prompt[written], to_write)) < to_write)
				to_write -= written;

		// read line of user text from the terminal
		before = time(); //timestamp for when user begins to re-enter text
		length = read(STDIN_FILENO, buffer, BUFF_LEN - 1);
		after = time();  //timestanp for when user finishes entering text

		// add null terminator if not already present
		buffer[length] = '\0';
		to_write = length;
		written = 0;

		// echo user text to terminal
		while((written = write(STDOUT_FILENO, &buffer[written], to_write)) < to_write)
				to_write -= written;

		// write a new line if the input string did not contain one
		if (buffer[length-1] != '\n')
				while(write(STDOUT_FILENO, "\n", 1) < 1);

		// calculate and print time taken to enter text
		after -= before;
		printf("%ldms\n", after);
	}

	return 0;
}
